<script>
    let user = { loggedIn: false };
    let x = 8;

    let cats = [
		{ id: 'J---aiyznGQ', name: 'Keyboard Cat' },
		{ id: 'z_AbfPXTKms', name: 'Maru' },
		{ id: 'OUtn3pvWmpg', name: 'Henri The Existential Cat' }
	];

    function toggle() {
        user.loggedIn = !user.loggedIn;
    }


    let promise = getRandomNumber();

	async function getRandomNumber() {
		const res = await fetch(`https://api.zhihuipufa.com/content/v1/content/achievement`);
		const text = await res.text();

		if (res.ok) {
			return text;
		} else {
			throw new Error(text);
		}
	}

	function handleClick() {
		promise = getRandomNumber();
	}

</script>

<ol>
    <li>
        {#if user.loggedIn}
            <button on:click={toggle}>
                Log out
            </button>
        {:else}
            <button on:click={toggle}>
                Log in
            </button>
        {/if}
    </li>
    <li>
        {#if x > 10}
            <p>{x} is greater than 10</p>
        {:else}
            {#if 5 > x}
                <p>{x} is less than 5</p>
            {:else}
                <p>{x} is between 5 and 10</p>
            {/if}
        {/if}
    </li>
    <li>
        <ul>
            {#each cats as cat, i (cat.id)} 
                <li>
                    <a target="_blank" href="https://www.youtube.com/watch?v={cat.id}">
                    {cat.name}
                    </a>
                </li>
            {/each}
        </ul>
    </li>
    <li>
        <button on:click={handleClick}>
            generate random number
        </button>
        
        <!-- replace this element -->
        {#await promise}
            <p> loading....</p>
        {:then number}
            <p>{number}</p>
        {:catch error}
            <p style="color: red">{error.message}</p>
        {/await}

        {#await promise then value}
            <p>the value is {value}</p>
        {/await}
    </li>
</ol>